const express = require("express");
const router = express.Router();
const user = require("../../model/user");
const multer = require("multer");
const JwtUtil = require("../../utils/jwt");

const jwt = require("jsonwebtoken");
const emailApi = require("../../utils/emailApi");

// const conn = require("../../config/db");
const { expressjwt: myjwt } = require("express-jwt");
const SECRET_KEY = "login2021";
const fs = require("fs");
const path = require("path");
const storage = multer.diskStorage({
    // 设置保存文件的路径
    destination: function (req, file, callback) {
        callback(null, "public/upload/");
    },
    filename: function (req, file, callback) {
        // 将保存文件名设置为 字段名 + 时间戳，
        // 比如 logo-1478521468943
        let suffix = file.mimetype.split("/")[1];
        //获取文件格式
        callback(null, file.fieldname + "-" + Date.now() + "." + suffix);
    },
});
const upload = multer({ storage: storage });
let { HOST_URL } = require("../../config/host");

const rep_email = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
router.post("/register", async (req, res) => {
    // 解构赋值
    let { user_acc, user_pwd, user_nick_name, create_time, email } = req.body;
    // console.log(email, 555);
    // 判断账号是否为邮箱
    if (rep_email.test(user_acc)) {
        // 生成随机字符串
        // 注册用户
        // console.log(email, 666);

        await user
            .register(user_acc, user_pwd, user_nick_name, create_time, email)
            .then((content) => {
                res.send(content);
            })
            .catch((error) => {
                res.send(error);
            });
    } else {
        // 数据格式不正确
        res.send({
            code: -1,
            msg: "该账号不是一个邮箱格式。888",
        });
    }
});

router.post("/login", async (req, res) => {
    // 解构赋值
    let { user_acc, user_pwd } = req.body;
    await user
        .login(user_acc, user_pwd)
        .then((content) => {
            // console.log(content.res[0].user_id);
            res.send(content);
        })
        .catch((error) => {
            res.send(error);
        });
});
router.post("/selectTokenUser", async (req, res) => {
    let { user_id } = req.body;
    console.log(user_id);

    await user
        .selectTokenUser(user_id)
        .then((content) => {
            res.send(content);
        })
        .catch((error) => {
            res.send(error);
        });
});
router.get("/send_code", async function (req, res) {
    let email = req.query.email;
    let rep = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    console.log(email);
    if (rep.test(email)) {
        emailApi.Email.getEmailCode(email).then(() => {
            res.send({
                code: 200,
                msg: "验证码发送成功。",
            });
        });
    } else {
        res.send({
            code: -1,
            msg: "邮箱格式不正确。",
        });
    }
});
// _____________________________________________
router.post("/save_img", async (req, res) => {
    let { user_id, user_img } = req.body;
    console.log(user_id, user_img);
    await user
        .modify_avator(user_id, user_img)
        .then((content) => {
            res.send(content);
        })
        .catch((err) => {
            res.send(err);
        });
});

router.post("/upload_img", upload.single("photo"), async (req, res) => {
    // 定义路径
    let token = req.headers["token"];
    let jwt = new JwtUtil(token);

    let result = jwt.verifyToken();
    console.log(result, "token");
    if (result == "err") {
        res.send({
            code: -1,
            msg: "登录已过期,请重新登录。",
        });
    } else {
        let picUrl = `${HOST_URL}/upload/${req.file.filename}`;
        // 返回上传头像文件路径
        res.send({
            code: 200,
            picUrl,
            msg: "用户头像上传成功。",
        });
    }
});

router.post("/delete_img", async (req, res) => {
    let { user_img } = req.body;
    return new Promise((resolve, reject) => {
        //通过slice方法，分割出图片前面的url地址
        let index = user_img.indexOf("upload");
        if (index > 0) {
            let temp_path = path.join(__dirname, "../../public", user_img.slice(index));
            console.log("--->", temp_path);
            // fs.unlink删除文件
            fs.unlink(temp_path, function (error) {
                if (error) {
                    resolve({
                        code: -1,
                        msg: "删除图片失败。",
                    });
                } else {
                    //删除图片文件成功
                    resolve({
                        code: 200,
                        msg: "删除图片成功。",
                    });
                }
            });
        } else {
            res.send({
                code: -1,
                msg: "默认头像不用删除。",
            });
        }
    });
});
router.post("/modify_msg", async (req, res) => {
    let { user_id, user_pwd, user_signature, user_phone, user_nick_name } = req.body;
    console.log(user_id, user_pwd, user_signature, user_phone, user_nick_name);

    await user
        .modifyMsg(user_id, user_pwd, user_signature, user_phone, user_nick_name)
        .then((content) => {
            res.send(content);
        })
        .catch((error) => {
            res.send(error);
        });
});
module.exports = router;
